﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Epic.HandyExtensions
{
    public static class ObjectExtensions
    {
#pragma warning disable 1591

        private static Lazy<BinaryFormatter> smBinaryFormatter = new Lazy<BinaryFormatter>();

        public static T As<T>(this object @this)
            where T : class
        {
            return @this as T;
        }

        public static Nullable<T> AsNullable<T>(this object @this)
            where T : struct
        {
            return @this as Nullable<T>;
        }

        public static bool Is(this object @this, object that)
        {
            return object.Equals(@this, that);
        }
        public static bool IsNot(this object @this, object that)
        {
            return !object.Equals(@this, that);
        }

        /// <summary>
        /// Deep copy, available to seralizable objects only.
        /// </summary>
        public static T DeepCopy<T>(this T @this)
        {
            var formatter = smBinaryFormatter.Value;
            using (var holder = new MemoryStream())
            {
                formatter.Serialize(holder, @this);
                holder.Position = 0;
                return (T)formatter.Deserialize(holder);
            }
        }

        public static T CastTo<T>(this object @this)
        {
            return (T)@this;
        }
    }
}
